//
//  PreferenceController.m
//  AMT media manager
//
//  Created by gift ku on 2/2/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PreferenceController.h"
#import "common.h"

NSString* PANE_ID[] = {
@"PreferenceGeneral",
@"PreferenceVideo",
@"PreferenceAudio",
};

#define PANE_COUNT  (sizeof(PANE_ID) / sizeof(PANE_ID[0]))
@interface PreferenceController()

- (void)initGeneralPane;
- (void)initAudioPane;
- (void)initVideoPane;

@end



@implementation PreferenceController

- (id)initWithAppController
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    if (self = [super initWithWindowNibName:@"Setting"]) {
		[self setWindowFrameAutosaveName:@"PreferencesWindow"];
		_defaults = [[NSUserDefaults standardUserDefaults] retain];
//		_appController = [appController retain];
//		_mainWindow = [mainWindow retain];
//		_movieView = [_mainWindow movieView];
    }
    return self;
}

- (void)windowDidLoad
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    NSToolbar* toolbar = [[NSToolbar alloc] initWithIdentifier:@"MPrefsToolbar"];
    [toolbar setDisplayMode:NSToolbarDisplayModeIconAndLabel];
    [toolbar setAllowsUserCustomization:FALSE];
    [toolbar setAutosavesConfiguration:FALSE];
    [toolbar setDelegate: self];
    [[self window] setToolbar:[toolbar autorelease]];
    [[self window] setShowsToolbarButton:FALSE];	
   
	[self initGeneralPane];
	[self initAudioPane];
	[self initVideoPane];
	
    NSString* identifier = [_defaults stringForKey:PreferencePaneKey];
    if (identifier ==nil) {
        identifier = PANE_ID[0];
    }
    [toolbar setSelectedItemIdentifier:identifier];
    [self selectPaneWithIdentifier:nil];
}

- (void)dealloc
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);   
    [_defaults synchronize];
    [_defaults release];
    [super dealloc];
}

- (void)selectPaneWithIdentifier:(NSString*)identifier
{
    //TRACE(@"%s \"%@\"", __PRETTY_FUNCTION__, identifier);
    BOOL initial = FALSE;
    if (!identifier) {
        initial = TRUE;
        identifier = [[[self window] toolbar] selectedItemIdentifier];
    }
	
    NSView* panes[PANE_COUNT] = {
        _generalPane,
        _videoPane,
        _audioPane,
    };
    int i;
    for (i = 0; i < PANE_COUNT; i++) {
        if ([identifier isEqualToString:PANE_ID[i]]) {
            break;
        }
    }
	
    NSWindow* window = [self window];
    NSRect frame = [window frame];
	
    NSView* cv = [window contentView];
    NSSize contentSize = [cv convertSize:[cv bounds].size toView:nil];
    NSSize frameSize = [cv convertSize:[panes[i] frame].size toView:nil];
    frameSize.height += frame.size.height - contentSize.height;
	frameSize.width += frame.size.width - contentSize.width;
	
    if (!initial) {
        frame.origin.x -= (frameSize.width - frame.size.width) / 2;
        frame.origin.y -= frameSize.height - frame.size.height;
    }
    frame.size = frameSize;
	
    if (!initial) {
        [[[[window contentView] subviews] objectAtIndex:0] removeFromSuperview];
    }
    [window setFrame:frame display:TRUE animate:!initial];
    [[window contentView] addSubview:panes[i]];
    [window setTitle:[[[[window toolbar] items] objectAtIndex:i] label]];
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark toolbar

- (NSToolbarItem*)toolbar:(NSToolbar*)toolbar
    itemForItemIdentifier:(NSString*)identifier willBeInsertedIntoToolbar:(BOOL)flag
{
    //TRACE(@"%s \"%@\" %@", __PRETTY_FUNCTION__, identifier,
    //      flag ? @"will be inserted" : @"will not be inserted");
    NSToolbarItem* item = [[[NSToolbarItem alloc] initWithItemIdentifier:identifier] autorelease];
	
    NSString* label[PANE_COUNT] = {
		@"General",
		@"Video",
		@"Audio",
    };
    
    int i;
    for (i = 0; i < PANE_COUNT; i++) {
        if ([identifier isEqualToString:PANE_ID[i]]) {
            [item setImage:[NSImage imageNamed:PANE_ID[i]]];
            [item setLabel:label[i]];
            [item setTarget:self];
            [item setAction:@selector(toolbarItemSelected:)];
            break;
        }
    }
    return item;
}

- (NSArray*)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    return [NSArray arrayWithObjects:PANE_ID count:PANE_COUNT];
}

- (NSArray*)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    return [self toolbarDefaultItemIdentifiers:toolbar];
}

- (NSArray*)toolbarSelectableItemIdentifiers:(NSToolbar*)toolbar
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    return [self toolbarDefaultItemIdentifiers:toolbar];
}

- (BOOL)validateToolbarItem:(NSToolbarItem*)toolbarItem { return TRUE; }

- (void)toolbarItemSelected:(id)sender
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    NSString* identifier = [[[self window] toolbar] selectedItemIdentifier];
    [self selectPaneWithIdentifier:identifier];
    [_defaults setObject:identifier forKey:PreferencePaneKey];
}

#pragma mark -
#pragma mark General

- (void)initGeneralPane
{
	NSString* temp;
	temp = [_defaults objectForKey:BackupDirectoryKey];
	if(temp == nil)
	{
		temp=@"";
	}
	[_backupDirectoryTextField setStringValue:temp];
	
	temp = [_defaults objectForKey:AudioDirectoryKey];
	if(temp == nil)
	{
		temp=@"";
	}
	[_audioDirectoryTextField setStringValue:temp];
	
	temp = [_defaults objectForKey:VideoDirectoryKey];
	if(temp == nil)
	{
		temp=@"";
	}
	[_videoDirectoryTextField setStringValue:temp];
	
	[_backupDirectoryMatrix selectCellAtRow:[_defaults integerForKey:BackupRadioKey] column:0];	
	[_backupDirectoryButton setEnabled:[_defaults integerForKey:BackupRadioKey]];
	[_audioDirectoryMatrix selectCellAtRow:[_defaults integerForKey:AudioRadioKey] column:0];
	[_audioDirectoryButton setEnabled:[_defaults integerForKey:AudioRadioKey]];
	[_videoDirectoryMatrix selectCellAtRow:[_defaults integerForKey:VideoRadioKey] column:0];
	[_videoDirectoryButton setEnabled:[_defaults integerForKey:VideoRadioKey]];
}

- (IBAction)openDirectoryAction:(id)sender
{
    //TRACE(@"%s", __PRETTY_FUNCTION__);
    NSOpenPanel* panel = [NSOpenPanel openPanel];
    //[panel setTitle:NSLocalizedString(@"Open Movie File", nil)];
    [panel setCanChooseFiles:FALSE];
    [panel setCanChooseDirectories:TRUE];
    [panel setAllowsMultipleSelection:FALSE];
    if (NSOKButton == [panel runModal]) {
		switch ([sender tag])
		{
			case 0:
				[_defaults setObject:[panel filename] forKey:BackupDirectoryKey];
				[_backupDirectoryTextField setStringValue:[panel filename]];
				break;		
			case 1:
				[_defaults setObject:[panel filename] forKey:AudioDirectoryKey];
				[_audioDirectoryTextField setStringValue:[panel filename]];		
				break;		
			case 2:
				[_defaults setObject:[panel filename] forKey:VideoDirectoryKey];
				[_videoDirectoryTextField setStringValue:[panel filename]];
				break;
		}
    }
}

- (IBAction)checkBackupDirectoryAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setObject:DefaultBackupDirectory forKey:BackupDirectoryKey];
		[_backupDirectoryTextField setStringValue:DefaultBackupDirectory];
		[_backupDirectoryButton setEnabled:FALSE];
	}
	else
	{
		[_backupDirectoryButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:BackupRadioKey];
}

- (IBAction)checkAudioDirectoryAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setObject:DefaultAudioDirectory forKey:AudioDirectoryKey];
		[_audioDirectoryTextField setStringValue:DefaultAudioDirectory];
		[_audioDirectoryButton setEnabled:FALSE];
	}
	else
	{
		[_audioDirectoryButton setEnabled:TRUE];
	}	
	[_defaults setInteger:selectedItem forKey:AudioRadioKey];
}

- (IBAction)checkVideoDirectoryAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setObject:DefaultVideoDirectory forKey:VideoDirectoryKey];
		[_videoDirectoryTextField setStringValue:DefaultVideoDirectory];
		[_videoDirectoryButton setEnabled:FALSE];
	}
	else
	{
		[_videoDirectoryButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:VideoRadioKey];
}

#pragma mark -
#pragma mark Audio

- (void)initAudioPane
{
	[_sampleRatePopUpButton selectItemAtIndex:[_defaults integerForKey:SampleRateKey]];
	[_bitRatePopUpButton selectItemAtIndex:[_defaults integerForKey:BitRateKey]];
	
	[_sampleRateMatrix selectCellAtRow:[_defaults integerForKey:SampleRateRadioKey] column:0];	
	[_sampleRatePopUpButton setEnabled:[_defaults integerForKey:SampleRateRadioKey]];
	[_bitRateMatrix selectCellAtRow:[_defaults integerForKey:BitRateRadioKey] column:0];	
	[_bitRatePopUpButton setEnabled:[_defaults integerForKey:BitRateRadioKey]];
}

- (IBAction)checkSampleRateAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setInteger:DefaultSampleRate forKey:SampleRateKey];
		[_sampleRatePopUpButton selectItemAtIndex:DefaultSampleRate];
		[_sampleRatePopUpButton setEnabled:FALSE];
	}
	else
	{
		[_sampleRatePopUpButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:SampleRateRadioKey];
}

- (IBAction)checkBitRateAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setInteger:DefaultBitRate forKey:BitRateKey];
		[_bitRatePopUpButton selectItemAtIndex:DefaultBitRate];
		[_bitRatePopUpButton setEnabled:FALSE];
	}
	else
	{
		[_bitRatePopUpButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:BitRateRadioKey];
}

- (IBAction)changeSampleRateAction:(id)sender
{
	NSInteger selectItem = [sender indexOfSelectedItem];
	[_defaults setInteger:selectItem forKey:SampleRateKey];
}

- (IBAction)changeBitRateAction:(id)sender
{
	NSInteger selectItem = [sender indexOfSelectedItem];
	[_defaults setInteger:selectItem forKey:BitRateKey];
}

#pragma mark -
#pragma mark Video

- (void)initVideoPane
{
	[_convertTypeMatrix selectCellAtRow:0 column:[_defaults integerForKey:ConvertTypeRadioKey]];
	[_hightWidthRatePopUpButton selectItemAtIndex:[_defaults integerForKey:HightWidthRateKey]];
	[_FPSPopUpButton selectItemAtIndex:[_defaults integerForKey:FPSKey]];
	
	[_hightWidthRateMatrix selectCellAtRow:[_defaults integerForKey:HightWidthRateRadioKey] column:0];	
	[_hightWidthRatePopUpButton setEnabled:[_defaults integerForKey:HightWidthRateRadioKey]];
	[_FPSMatrix selectCellAtRow:[_defaults integerForKey:FPSRadioKey] column:0];	
	[_FPSPopUpButton setEnabled:[_defaults integerForKey:FPSRadioKey]];
	
	[_preserveAspectRatioCheck setIntegerValue:[_defaults integerForKey:PreserveAspectRatioKey]];
}

- (IBAction)checkConvertTypeAction:(id)sender
{
	NSInteger selectedItem = [sender selectedColumn];	
	[_defaults setInteger:selectedItem forKey:ConvertTypeRadioKey];
}

- (IBAction)checkHightWidthRateAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setInteger:DefaultHightWidthRate forKey:HightWidthRateKey];
		[_hightWidthRatePopUpButton selectItemAtIndex:DefaultHightWidthRate];
		[_hightWidthRatePopUpButton setEnabled:FALSE];
	}
	else
	{
		[_hightWidthRatePopUpButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:HightWidthRateRadioKey];
}

- (IBAction)checkFPSAction:(id)sender
{
	NSInteger selectedItem = [sender selectedRow];
	if(selectedItem==0)
	{
		[_defaults setInteger:DefaultFPS forKey:FPSKey];
		[_FPSPopUpButton selectItemAtIndex:DefaultFPS];
		[_FPSPopUpButton setEnabled:FALSE];
	}
	else
	{
		[_FPSPopUpButton setEnabled:TRUE];
	}
	[_defaults setInteger:selectedItem forKey:FPSRadioKey];
}

- (IBAction)changeHightWidthRateAction:(id)sender
{
	NSInteger selectItem = [sender indexOfSelectedItem];
	[_defaults setInteger:selectItem forKey:HightWidthRateKey];
}

- (IBAction)changeFPSAction:(id)sender
{
	NSInteger selectItem = [sender indexOfSelectedItem];
	[_defaults setInteger:selectItem forKey:FPSKey];
}

- (IBAction)checkPreserveAspectRatioAction:(id)sender
{
	NSInteger number = [sender integerValue];
	[_defaults setInteger:number forKey:PreserveAspectRatioKey];
}


@end
